<template>
	<div class="centermap">
		<!-- <div class="maptitle">
			<div class="slanted_bar_left"></div>
			<span class="titletext">{{ maptitle }}</span>
			<div class="slanted_bar_right"></div>
		</div> -->
		<div class="mapwrap">
			<!-- 按钮 
			<div class="return_china_map_button" @click="returnChinaMap()" v-if="code !== 'china'">
				返回
			</div>-->

			<!-- 地图 -->
			<Echart id="CenterMap" :options="options" ref="CenterMap" />
		</div>
	</div>
</template>

<script>
import { regionCodes, getNameByRegionCode } from "../../utils/map/regionCodes";
import * as echarts from "echarts";
import { GETNOBASE } from "api";
export default {
	data() {
		return {
			maptitle: "生源分布图",
			options: {},
			code: "china", // china 代表中国 其他地市是行政编码
			echartBindClick: false,
			isSouthChinaSea: false, // 是否要展示南海群岛  修改此值请刷新页面
			lastHighlighted: null,
			lastClicked: null,
		};
	},
	created() { },

	mounted() {
		// console.log(regionCodes);
		this.getData("china");
	},
	methods: {
		getData(regionCode) {
			this.$axios.get("/api/result/province").then((res) => {
				console.log("生源地分布", res);
				if (res.code == 0) {
					this.getGeojson(regionCode, res.data);
					this.bindMapClickEvent();
				} else {
					this.$Message.warning(res.message);
				}
			});
		},
		/*
		获取geojson，绘制地图
		*/
		async getGeojson(regionCode, regionData) {
			this.code = regionCode;
			// 如果要展示南海群岛并且展示的是中国
			let geoname = regionCode;
			if (this.isSouthChinaSea && regionCode == "china") {
				geoname = "chinaNanhai";
			}
			// 如果有注册地图的话就不用再注册了
			let mapjson = echarts.getMap(regionCode);
			if (mapjson) {
				mapjson = mapjson.geoJSON;
			} else {
				// 读取静态资源 项目目录/public/map-geojson/${geoname}.json
				mapjson = await GETNOBASE(`./map-geojson/${geoname}.json`).then((res) => {
					return res;
				});
				echarts.registerMap(regionCode, mapjson);
			}
			// console.log("map_json", regionCode, mapjson);

			let seriesMapData = []; // 构造适合Echarts绘制的数据
			let cityCenterData = []; // 构造省份中心点数据
			for (let key in regionData) {
				let cityCenter = {}; // 根据geojson获取省份中心点
				mapjson.features.map((item) => {
					cityCenter[item.properties.name] =
						item.properties.centroid || item.properties.center;
				});

				let name = getNameByRegionCode(key);

				seriesMapData.push({
					name: name,
					value: regionData[key]
				});

				if (cityCenter[name]) {
					cityCenterData.push({
						name: name,
						value: cityCenter[name].concat(regionData[key]),
					});
				}
			}

			this.drawMap(regionCode, seriesMapData, cityCenterData);
		},
		drawMap(regionCode, seriesMapData, cityCenterData) {
			// 绘制地图
			// console.log("seriesMapData", seriesMapData);
			// console.log("cityCenterData", cityCenterData);

			let top = 45;
			let zoom = 1.17;
			let option = {
				backgroundColor: "rgba(0,0,0,0)",
				tooltip: {
					show: false,
				},
				legend: {
					show: false,
				},
				// 颜色映射
				visualMap: {
					left: 20,
					bottom: 20,
					pieces: [
						{ gte: 200, label: "> 200" }, // 不指定 max，表示 max 为无限大（Infinity）。
						{ gte: 150, lte: 199, label: "150 - 200" },
						{ gte: 100, lte: 149, label: "100 - 150" },
						{ gte: 50, lte: 99, label: "50 - 100" },
						{ gte: 10, lte: 49, label: "10 - 50" },
						{ lte: 9, label: "< 10" }, // 不指定 min，表示 min 为无限大（-Infinity）。
					],
					inRange: {
						// 渐变颜色，从小到大
						color: [
							"#d5ead7",
							"#96d3af",
							"#50b97d",
							"#009A44",
							"#017f3c",
							"#015C31",
						],
					},
					textStyle: {
						color: "#005B30",
					},
				},
				geo: {
					map: regionCode,
					roam: false,
					selectedMode: false,
					zoom: zoom,
					top: top,
					// aspectScale: 0.78,
					show: false,
				},
				series: [
					{
						name: "MAP",
						type: "map",
						map: regionCode,
						// aspectScale: 0.78,
						data: seriesMapData,
						// data: [1,100],
						zoom: zoom,
						roam: true, // 可以滚轮缩放和平移
						scaleLimit: { // 滚轮缩放极限
							min: 1,
							max: 30
						},
						geoIndex: 1,
						top: top,
						showLegendSymbol: false, // 不显示中心点
						selectedMode: "single", //是否允许选中多个区域
						// 选中样式
						select: {
							disabled: false,
							itemStyle: {
								areaColor: "#a23e0a",
								borderColor: "#fff",
								borderWidth: 1,
								// shadowColor: "#D0D0D0",
								// shadowOffsetX: -5,
								// shadowOffsetY: 5,
								// shadowBlur: 10,
							},
							// 标签
							label: {
								show: false,
								fontSize: 16,
								position: "inside",
								textBorderColor: "#fff",
								textShadowColor: "#00000050",
								textShadowBlur: 10,
								textBorderWidth: 0,
								color: "#005B30",
								formatter: function (val) {
									// console.log(val)
									if (val.data != undefined) {
										let text = val.name.slice(0, 2);
										if (text == "黑龙") text = "黑龙江";
										return text;
									} else {
										return "";
									}
								},
							}
						},
						// 提示框
						tooltip: {
							show: true,
							formatter: function (params) {
								let provinceData = regionCodes[params.name];
								if (provinceData) {
									if (params.data) {
										return params.name + "：" + params.data["value"] + "人";
									} else {
										return params.name;
									}
								} else {
									return "";
								}

							},
							backgroundColor: "#f8faf7",
							borderColor: "#009a44",
							borderWidth: 1.5,
							shadowColor: "#00000060",
							shadowOffsetX: 0,
							shadowOffsetY: 0,
							shadowBlur: 12,
							textStyle: {
								fontSize: 20,
								color: "#233a18",
							},
						},
						// 地图区域名标签
						label: {
							fontSize: 11,
							offset: [0, 2],
							position: "bottom",
							textborderColor: "#009a44",
							borderWidth: 1.5,
							textShadowColor: "#00000050",
							textShadowBlur: 10,
							textBorderWidth: 0,
							color: "#005B30",
							show: false,
							formatter: function (val) {
								// console.log(val)
								if (val.data != undefined) {
									let text = val.name.slice(0, 2);
									if (text == "黑龙") text = "黑龙江";
									return text;
								} else {
									return "";
								}
							},
							rich: {},
						},
						// 鼠标移入样式
						emphasis: {
							label: {
								show: false, // 不显示
							},
							itemStyle: {
								areaColor: "#b3612f",
								borderColor: "#fff",
								borderWidth: 1,
							},
						},
						// 地区块样式
						itemStyle: {
							borderColor: "#fff",
							borderWidth: 1,
							areaColor: "#dae5db",
							// shadowColor: "rgba(128, 217, 248, .3)",
							// shadowOffsetX: -2,
							// shadowOffsetY: 2,
							// shadowBlur: 10,
						},
						animation: true,
					},
					/* 中心点高亮并显示省份名称 
					{
						data: cityCenterData,
						type: "effectScatter",
						coordinateSystem: "geo",
						symbolSize: function (val) {
							return 4;
							// return val[2] / 50;
						},
						legendHoverLink: true,
						showEffectOn: "render",
						rippleEffect: {
							// period: 4,
							scale: 6,
							color: "rgba(255,255,255,1)", // 点外圈涟漪颜色
							brushType: "fill",
						},
						// 提示框 “省份名：数值”
						tooltip: {
							show: true,
							formatter: function (params) {
								if (params.data) {
									return params.name + "：" + params.data["value"][2];
								} else {
									return params.name;
								}
							},
							backgroundColor: "rgba(0,0,0,.6)",
							borderColor: "rgba(147, 235, 248, .8)",
							textStyle: {
								color: "#FFF",
							},
						},
						// 区域名标签
						label: {
							formatter: (param) => {
								let text = param.name.slice(0, 2);
								if (text == "黑龙") text = "黑龙江";
								return text;
							},

							fontSize: 11,
							offset: [0, 2],
							position: "bottom",
							textBorderColor: "#fff",
							textShadowColor: "#000",
							textShadowBlur: 10,
							textBorderWidth: 0,
							color: "#FFF",
							show: true,
						},
						// colorBy: "data",
						// 图形样式
						itemStyle: {
							color: "rgba(255,255,255,1)", // 点颜色
							borderColor: "rgba(255,255,255,2)",
							borderWidth: 4, // 描边宽度
							shadowColor: "rgba(0,0,0,1)", // 阴影颜色
							shadowBlur: 10, // 阴影模糊大小
							opacity: 1, // 透明度
						},
					},*/

				],
				//动画效果
				// animationDuration: 1000,
				// animationEasing: 'linear',
				// animationDurationUpdate: 1000
			};
			this.options = option;
		},
		message(text) {
			this.$Message({
				text: text,
				type: "warning",
			});
		},
		bindMapClickEvent() {
			// 绑定地图点击事件

			// console.log("echartBindClick", this.echartBindClick);
			// 若已绑定过，不再重复绑定
			if (this.echartBindClick) return;

			// 高亮BUG弥补
			this.$refs.CenterMap.chart.on("mousemove", (params) => {
				// console.log("mousemove", params.name);
				if (this.lastHighlighted != params.name) {
					this.$refs.CenterMap.chart.dispatchAction({
						type: 'downplay',
						seriesIndex: 0,
						name: this.lastHighlighted,
					});
					this.lastHighlighted = params.name;
				}
				this.$refs.CenterMap.chart.dispatchAction({
					type: 'highlight',
					seriesIndex: 0,
					name: params.name,
				});
			});
			this.$refs.CenterMap.chart.on("mouseout", (params) => {
				this.$refs.CenterMap.chart.dispatchAction({
					type: 'downplay',
					seriesIndex: 0,
					name: params.name,
				});
			});
			// 单击切换到级地图，当mapCode有值,说明可以切换到下级地图
			this.$refs.CenterMap.chart.on("click", (params) => {
				// console.log("params", params);

				let regionCode = regionCodes[params.name].adcode;

				// 若点击的是已选中的地区，返回中国地图
				if (regionCode == this.code) {
					this.returnChinaMap();
					return;
				}

				// 获取省份中心点
				let mapjson = echarts.getMap("china").geoJSON;
				let center;
				for (let i = 0; i < mapjson.features.length; i++) {
					if (mapjson.features[i].properties.name == params.name) {
						center = mapjson.features[i].properties.centroid || mapjson.features[i].properties.center;
						break;
					}
				}

				// 沿中心点放大
				let option = this.$refs.CenterMap.chart.getOption();
				option.series[0].center = [center[0], center[1]];
				option.series[0].layoutCenter = ['50%', '50%'];
				let zoom;
				// 控制放大比例
				if (["香港特别行政区", "澳门特别行政区"].includes(params.name)) {
					zoom = 30;
				} else if (["上海市", "北京市", "天津市"].includes(params.name)) {
					zoom = 15;
				} else if (["海南省", "台湾省"].includes(params.name)) {
					zoom = 10;
				} else if (["贵州省", "江西省", "河南省", "山东省", "辽宁省", "安徽省", "福建省", "江苏省", "浙江省", "重庆市", "宁夏回族自治区"].includes(params.name)) {
					zoom = 7;
				} else if (["云南省", "广西壮族自治区", "湖南省", "陕西省", "山西省", "河北省", "吉林省", "湖北省", "广东省"].includes(params.name)) {
					zoom = 5;
				} else if (["西藏自治区", "青海省", "黑龙江省", "四川省", "甘肃省"].includes(params.name)) {
					zoom = 3;
				} else {
					zoom = 2;
				}
				option.series[0].zoom = zoom;
				this.$refs.CenterMap.chart.setOption(option);

				// 修改code使返回按钮显示
				this.code = regionCode;

				// 通知其他组件，以更新数据
				this.$emit("region-selected", regionCode);
			});
			this.echartBindClick = true;
		},
		returnChinaMap() {
			this.getData("china");
			this.$emit("region-selected", "china");
		},
	},
};
</script>
<style lang="scss" scoped>
.centermap {
	margin-bottom: 0;

	.maptitle {
		height: 60px;
		display: flex;
		justify-content: center;
		padding-top: 10px;
		box-sizing: border-box;

		.titletext {
			font-size: 28px;
			font-weight: 900;
			letter-spacing: 6px;
			background: linear-gradient(92deg,
					#015c31 0%,
					#009a44 48.8525390625%,
					#015c31 100%);
			-webkit-background-clip: text;
			-webkit-text-fill-color: transparent;
			margin: 0 10px;
		}

		.slanted_bar_left,
		.slanted_bar_right {
			background-size: 100% 100%;
			width: 29px;
			height: 20px;
			margin-top: 8px;
		}

		.slanted_bar_left,
		.slanted_bar_right {
			background: url("../../assets/img/center_slanted_bar_left.png") no-repeat;
		}

		.slanted_bar_right {
			transform: rotateY(180deg);
		}
	}

	.mapwrap {
		height: 100%;
		width: 100%;
		// padding: 0 0 10px 0;
		box-sizing: border-box;
		position: relative;

		.return_china_map_button {
			position: absolute;
			right: 20px;
			top: -46px;
			width: 80px;
			height: 28px;
			border: 1px solid #005b30;
			border-radius: 10px;
			color: #005b30;
			text-align: center;
			line-height: 26px;
			letter-spacing: 6px;
			text-indent: 6px;
			cursor: pointer;
			box-shadow: 0 2px 4px #eee,
				0 0 6px #eee;
		}
	}
}
</style>